<template>
  <view :data-theme="globPrimary">
    <u-navbar title="购物车"></u-navbar>
    <view class="order-wrapper">
      <edu-mescroll-body
        @init="mescrollInit"
        height="calc(100vh - 44px - 98rpx)"
        @down="refresh"
        :up="upOption"
        @up="reachBottom"
      >
        <view class="order-item" v-for="(out, outIndex) in orderList" :key="outIndex">
          <view class="u-flex head u-border-bottom">
            <view class="name u-line-1">{{ out.school_name }}</view>
          </view>
          <view class="list u-flex" v-for="item in out.course_list" :key="item.id">
            <courseImage
              width="260"
              height="144"
              :image="item.cover_url"
              :courseType="item.course_type"
              :courseTypeText="item.course_type_text"
            ></courseImage>
            <view class="content">
              <view class="title u-line-2">
                <u-image
                  v-if="item.has_course_card === 1"
                  width="72"
                  height="28"
                  src="@/pageCourse/static/images/lessoncard_icon.png"
                ></u-image>
                {{ item.title }}
              </view>
              <view class="u-flex u-row-right">
                <view class="buy-time">{{ `${item.section_count}课时` }}</view>
              </view>
              <view class="u-flex u-row-between">
                <view class="price">
                  <block v-if="userInfo.is_vip == 1">vip:</block>
                  {{ item.user_price | formatCurrency }}
                </view>

                <view class="buy-time" v-if="item.term_time == 0">永久有效</view>
                <view class="buy-time" v-if="item.term_time < 10000 && item.term_time != 0"
                  >购买之日起<label style="color: #f54030">{{ item.term_time }}</label
                  >天内有效</view
                >
                <view class="buy-time" v-if="item.term_time >= 10000"
                  >{{ item.term_time | handleTime }}前有效</view
                >
              </view>
            </view>
          </view>
          <view class="u-flex coupon-cell">
            <view class="title">卡券</view>
            <view class="info" v-if="$u.test.empty(out.best_coupon)">无卡券可使用</view>
            <template v-else>
              <view class="info is" v-if="out.best_coupon.is_coupon == 1" @click="openCoupon(out)">
                <template v-if="out.best_coupon.coupon_type == 1">
                  满{{ parseFloat(out.best_coupon.maxprice) }}减{{
                    parseFloat(out.best_coupon.price)
                  }}
                </template>
                <template v-else-if="out.best_coupon.coupon_type == 2">
                  {{ parseFloat(out.best_coupon.discount) }}折
                </template>
              </view>
              <view class="info is" v-else @click="openCoupon(out)">未使用卡券</view>
            </template>
            <u-icon name="arrow-right" color="#B7BAC1"></u-icon>
          </view>
          <view class="u-flex price-cell">
            <view class="disc">优惠:{{ out.discount_total | formatCurrency }}</view>
            <view class="text">合计:</view>
            <view class="total">{{ out.total | formatCurrency }}</view>
          </view>
        </view>
        <u-cell-group :border="false" style="margin-top: 22rpx">
          <u-cell-item
            v-if="credit_arr.length != 0"
            title="积分"
            :value="text"
            :border-bottom="false"
            hover-class="none"
            :value-style="{ color: isCoupon == 0 ? '' : '#FF8A52' }"
            @click="openCoupon2"
          ></u-cell-item>
        </u-cell-group>
      </edu-mescroll-body>
    </view>

    <!-- 机构的卡卷 -->
    <u-popup
      v-model="couponPopup"
      mode="bottom"
      border-radius="14"
      height="70%"
      @close="closeCoupon"
      class="coupon-wrapper"
    >
      <view class="coupon-title">卡券</view>
      <view class="coupon-list">
        <scroll-view scroll-y="true" class="coupon-scroll">
          <view class="item" v-for="(out, listIndex) in couponList" :key="listIndex">
            <view class="title" v-if="out.useful == 1">{{ out.coupon_type_text }}</view>
            <!-- 可用 -->
            <template v-if="out.useful == 1">
              <view
                class="u-flex ticket"
                :class="couponBgColorClass[item.coupon_type]"
                v-for="item in out.list"
                :key="item.id"
              >
                <view class="left">
                  <view class="top" v-if="item.coupon_type == 1">
                    <text class="big">{{ item.price | formatCurrency }}</text>
                    满{{ parseFloat(item.maxprice) }}减{{ parseFloat(item.price) }}
                  </view>
                  <view class="top" v-else-if="item.coupon_type == 2">
                    <text class="big">{{ parseFloat(item.discount) }}折</text>
                  </view>
                  <view class="type u-line-1">仅限{{ item.school_name }}使用</view>
                  <view v-if="item.use_etime" class="date u-line-1"
                    >有效期{{ item.use_stime | timeFormat('yyyy.mm.dd') }}至{{
                      item.use_etime | timeFormat('yyyy.mm.dd')
                    }}</view
                  >
                  <view v-else class="date u-line-1">永久有效</view>
                </view>
                <view class="u-flex u-row-center right">
                  <view
                    class="use active"
                    :round="true"
                    v-if="couponId == item.id"
                    @click="cancelCoupon(item)"
                    >取消使用</view
                  >
                  <view class="use" :round="true" v-else @click="useCoupon(item)">使用</view>
                </view>
              </view>
            </template>
          </view>
          <view class="u-margin-top-20 u-flex u-row-center" v-if="couponLoading"
            ><u-loading mode="flower" :show="couponLoading"></u-loading
          ></view>
          <edu-empty v-if="couponEmpty"></edu-empty>
        </scroll-view>
      </view>
    </u-popup>
    <view class="bottom-placeholder">
      <view class="u-flex bottom-navbar">
        <view>优惠：{{ sumDiscount | formatCurrency }}</view>
        <view class="total">
          合计：
          <text class="num">{{ sumPrice | formatCurrency }}</text>
        </view>
        <view class="btn" @click="settlement">提交订单</view>
      </view>
    </view>

    <!-- 积分弹窗 -->
    <u-popup v-model="couponPopup2" mode="bottom" border-radius="34" height="723">
      <view class="coin">
        <view class="coin-title">积分抵扣</view>
        <scroll-view scroll-y="true" class="scrollY" style="height: 500rpx; width: 100%">
          <u-radio-group v-model="paywayRadio" size="44" style="width: 100%">
            <view class="radio-item" v-for="(item, index) in credit_arr" :key="index">
              <view class="radio_li">
                <view class="left-ltem addClass" v-if="index == 0"
                  >可使用积分 {{ item.credit }}</view
                >
                <view class="left-ltem" v-else>{{ item.credit }}积分</view>
                <view class="right-item" @click="change(item, item.num, index)">
                  <view class="can-num">可抵￥{{ item.num }}</view>
                  <u-radio :name="index" :active-color="globPrimaryColor"></u-radio>
                </view>
              </view>
            </view>
          </u-radio-group>
        </scroll-view>
        <view class="sure" @click="sureClick()">确定</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import courseImage from '@/components/common/courseImage.vue'
import { mapGetters } from 'vuex'
export default {
  components: {
    courseImage,
  },
  data() {
    return {
      typeClass: { 1: 'video', 2: 'live', 3: 'multipart', 4: 'classes' },
      couponBgColorClass: { 1: 'youhui', 2: 'dazhe' },
      orderList: [],
      couponList: [],
      couponId: 0,
      couponPopup: false,
      couponLoading: false,
      couponEmpty: false,
      optionId: '',
      upOption: {
        isLock: true,
        empty: {
          tip: '购物车是空的',
        },
      },
      isCoupon: 1,
      credit_num: '',
      couponPopup2: false,
      paywayRadio: 0,

      credit_arr: [],
      save_credit: [],
      credit_redeem: 1,
      str_credit: '{}',

      save_item: {},
      save_index: '',
      new_name: 0,
      isSure: 0,
    }
  },
  watch: {
    orderList: {
      deep: true,
      handler() {
        this.schoolDiscount()
      },
    },
  },
  computed: {
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      userInfo: 'user/getUserInfo',
    }),
    text() {
      if (this.isCoupon == 0) {
        return `可抵扣￥${this.credit_num}`
      } else {
        return `可抵扣￥${this.credit_num}`
      }
    },
    //计算总价-优惠后的价格
    sumPrice() {
      let total = this.orderList.reduce((pre, cur) => {
        return pre + cur.total_price
      }, 0)
      return (total * 100 - this.sumDiscount * 100 - this.credit_num * 100) / 100
    },
    //计算优惠的总价
    sumDiscount() {
      return this.orderList.reduce((pre, cur) => {
        return pre + parseFloat(cur.discount_total)
      }, 0)
    },
  },
  onLoad(options) {
    this.optionId = options.id
  },
  filters: {
    fill_credit(val, value1) {
      return val * value1
    },
    handleTime(timeStamp) {
      if (timeStamp > 0) {
        var date = new Date()
        date.setTime(timeStamp * 1000)
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        m = m < 10 ? '0' + m : m
        var d = date.getDate()
        d = d < 10 ? '0' + d : d
        var h = date.getHours()
        h = h < 10 ? '0' + h : h
        var minute = date.getMinutes()
        var second = date.getSeconds()
        minute = minute < 10 ? '0' + minute : minute
        second = second < 10 ? '0' + second : second
        return y + '年' + m + '月' + d + '日'
      } else {
        return ''
      }
    },
  },
  options: { styleIsolation: 'shared' },
  methods: {
    getcreite() {
      this.paywayRadio = 0
      let params = this.orderList.map((vo) => {
        let query = {
          course_ids: vo.course_list.map((item) => item.id).toString(),
          coupon: '',
          ticket: '',
        }
        if (vo.ticket_id) {
          if (!this.$u.test.empty(vo.best_coupon)) {
            if (vo.best_coupon.is_coupon == 1) {
              query = {
                ...query,
                ticket: vo.best_coupon.id,
              }
            }
          }
        } else {
          if (!this.$u.test.empty(vo.best_coupon)) {
            if (vo.best_coupon.is_coupon == 1) {
              query = {
                ...query,
                coupon: vo.best_coupon.id,
              }
            }
          }
        }
        return query
      })
      let ids = params.map((item) => item.course_ids)
      let tid = params.map((item) => item.ticket).filter((item) => item)
      let cid = params.map((item) => item.coupon).filter((item) => item)
      this.$edu.api
        .getCartCredit({
          course: ids.toString(),
          coupon: cid.toString(),
          ticket: tid.toString(),
        })
        .then((res) => {
          this.credit_arr = res.data
          if (this.credit_arr.length != 0) {
            this.credit_num = this.credit_arr[0].num
            this.isCoupon = 1
            this.str_credit = JSON.stringify(this.credit_arr[0])
          } else {
            this.credit_num = 0
            this.str_credit = '{}'
          }
          this.credit_arr.map((el, key) => (key == 0 ? (el.isChose = true) : (el.isChose = false)))
          this.credit_arr.forEach((el, key) => {
            if (el.isChose) {
              this.save_index = key
            }
          })
        })
        .catch(() => {
          this.credit_num = 0
          this.str_credit = '{}'
        })
    },
    openCoupon2() {
      this.couponPopup2 = true
      this.paywayRadio = this.save_index
    },
    change(item, name, index) {
      if (item.isChose) {
        this.paywayRadio = null
        this.credit_arr.forEach((el) => (el.isChose = false))
        this.isSure = -1
      } else {
        this.paywayRadio = index
        this.credit_arr.forEach((el, key) =>
          index == key ? (el.isChose = true) : (el.isChose = false)
        )
        this.new_name = name
        this.isSure = 1
      }
      this.save_item = item
    },
    sureClick() {
      if (this.isSure == -1) {
        this.credit_num = 0
        this.isCoupon = 0
        this.str_credit = '{}'
        this.couponPopup2 = false
        this.save_index = null
      } else if (this.isSure == 1) {
        this.str_credit = JSON.stringify(this.save_item)
        this.isCoupon = 1
        this.credit_num = this.new_name
        this.couponPopup2 = false
        this.credit_arr.forEach((el, key) => {
          if (this.save_item.num == el.num) {
            this.save_index = key
          }
        })
      } else {
        this.isSure == 0
      }
      {
        this.couponPopup2 = false
      }
    },
    // 下拉刷新
    refresh() {
      this.mescroll.resetUpScroll()
    },
    reachBottom() {
      this.$edu.api
        .getOrderCourseCart({
          course_ids: this.optionId,
        })
        .then((res) => {
          const { data } = res
          var credit_arr = data.credit
          credit_arr.map((el, key) => (key == 0 ? (el.isChose = true) : (el.isChose = false)))
          this.save_credit = credit_arr
          if (data.credit.length != 0) {
            this.credit_num = data.credit[0].num
          }
          data.cart.forEach((item) => {
            if (!this.$u.test.empty(item.best_coupon)) {
              this.$set(item.best_coupon, 'is_coupon', 1)
              if (this.$edu.test.isDef(item.best_coupon.ticket_id)) {
                this.$set(item, 'ticket_id', item.best_coupon.ticket_id)
              } else {
                this.$set(item, 'ticket_id', 0)
              }
            } else {
              this.$set(item, 'ticket_id', 0)
            }
          })
          this.orderList = data.cart
          this.mescroll.endSuccess(data.cart.length, false)
          this.getcreite()
        })
    },
    // 计算机构的是否有优惠折扣
    schoolDiscount() {
      let discountTotal = 0
      let total = 0
      this.orderList.forEach((item, index) => {
        if (this.$u.test.empty(item.best_coupon)) {
          discountTotal = 0
          total = item.total_price
        } else {
          if (item.best_coupon.is_coupon == 1) {
            if (item.best_coupon.coupon_type == 1) {
              discountTotal = parseFloat(item.best_coupon.price)
            } else if (item.best_coupon.coupon_type == 2) {
              let discount = item.best_coupon.discount
              let price = item.total_price
              discountTotal = parseFloat(price - price * (discount / 10)).toFixed(2)
            }
            total = (item.total_price * 1000 - parseFloat(discountTotal * 1000)) / 1000
          } else {
            discountTotal = 0
            total = item.total_price
          }
        }
        this.$set(item, 'total', total)
        this.$set(item, 'discount_total', discountTotal)
      })
    },
    // 获取机构的卡卷
    getCoupon(out) {
      this.couponPopup = true
      this.couponLoading = true
      this.couponEmpty = false
      this.$edu.api
        .getCourseCouponSchoolUser({
          mhm_id: out.mhm_id,
          price: out.total_price,
          group: 1,
        })
        .then((res) => {
          let data = res.data
          // 过滤空
          data = data.filter((item) => {
            return !this.$u.test.empty(item.list)
          })
          if (this.$u.test.empty(data)) this.couponEmpty = true
          this.couponLoading = false
          this.couponList = data
        })
        .catch((res) => {
          this.couponLoading = false
        })
    },
    changeCoupon(flag, item) {
      this.$set(item, 'btmFlag', !flag)
    },
    // 打开卡卷信息
    openCoupon(out) {
      if (out.best_coupon.is_coupon == 1) {
        this.couponId = out.best_coupon.id
      }
      this.getCoupon(out)
    },
    // 关闭卡卷弹窗
    closeCoupon() {
      this.couponList = []
    },
    // 使用卡卷
    useCoupon(out) {
      this.couponId = out.id
      this.orderList.forEach((item) => {
        if (item.mhm_id == out.mhm_id) {
          item.best_coupon = out
          item.best_coupon = Object.assign({}, item.best_coupon, {
            is_coupon: 1,
          })
          if (this.$edu.test.isDef(out.ticket_id)) {
            item.ticket_id = out.ticket_id
          } else {
            item.ticket_id = 0
          }
        }
      })
      this.getcreite()
      // 关闭弹窗
      this.couponPopup = false
    },
    // 取消使用
    cancelCoupon(out) {
      this.couponId = 0
      this.orderList.forEach((item) => {
        if (item.mhm_id == out.mhm_id) {
          item.best_coupon = Object.assign({}, item.best_coupon, {
            is_coupon: 0,
          })
          item.ticket_id = 0
        }
      })
      // 关闭弹窗
      this.getcreite()
      this.couponPopup = false
    },
    // 提交
    settlement() {
      let course_arr = this.orderList.map((item) => {
        let query = {
          course_ids: item.course_list.map((subItem) => subItem.id).toString(),
          coupon: 0,
          ticket: 0,
        }
        if (item.ticket_id) {
          if (!this.$u.test.empty(item.best_coupon)) {
            if (item.best_coupon.is_coupon == 1) {
              query = {
                ...query,
                ticket: item.best_coupon.id,
              }
            }
          }
        } else {
          if (!this.$u.test.empty(item.best_coupon)) {
            if (item.best_coupon.is_coupon == 1) {
              query = {
                ...query,
                coupon: item.best_coupon.id,
              }
            }
          }
        }
        return query
      })
      this.$edu.api
        .postOrderCourseCart({
          course: course_arr,
          credit: this.str_credit,
        })
        .then((res) => {
          if (res.data.need_pay == 0) {
            this.$u.route({
              type: 'switchTab',
              url: '/pages/course/index',
            })
          } else {
            this.$u.route({
              type: 'redirectTo',
              url: 'pages/pay',
              params: {
                no: res.data.order_no,
                payment: res.data.payment,
                redirect_type: 'order',
              },
            })
          }
        })
        .catch((res) => {
          this.$u.toast(res.msg)
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.order-wrapper {
  .order-item {
    background-color: #fff;
    padding-bottom: 35rpx;
    margin-top: 20rpx;
    /deep/.u-checkbox__label {
      display: none;
    }
    .head {
      height: 98rpx;
      margin-bottom: 32rpx;
      padding: 0 30rpx;
      .name {
        font-size: 30rpx;
        font-weight: 500;
        color: $edu-main-color;
      }
      .btn {
        font-size: 26rpx;
        font-weight: 400;
        color: $edu-main-color;
      }
    }
    .list + .list {
      margin-top: 24rpx;
    }
    .list {
      /* #ifdef MP-WEIXIN */
      display: flex;
      /* #endif */
      padding: 0 30rpx;
      .content {
        flex: 1;
        margin-left: 16rpx;
        .title {
          height: 72rpx;
          font-size: 28rpx;
          font-weight: 400;
          color: #333333;
          line-height: 36rpx;
          margin-bottom: 38rpx;
          .u-image {
            float: left;
            margin-top: 4rpx;
            margin-right: 4rpx;
          }
        }
        .price {
          font-size: 26rpx;
          font-weight: 500;
          color: $edu-price-color;
        }
        .buy-time {
          font-size: 26rpx;
          color: #909399;
        }
        .assist {
          font-size: 22rpx;
          font-weight: 400;
          color: #909399;
        }
      }
    }
    .coupon-cell {
      padding: 0 30rpx;
      margin-top: 40rpx;
      font-size: 28rpx;
      font-weight: 400;
      .title {
        color: #606266;
      }
      .info {
        margin-left: auto;
        color: #909399;
        margin-right: 20rpx;
        &.is {
          color: #ff8a52;
        }
      }
    }
    .price-cell {
      padding: 0 30rpx;
      margin-top: 50rpx;
      .disc {
        margin-left: auto;
        font-size: 26rpx;
        font-weight: 400;
        color: #909399;
        margin-right: 32rpx;
      }
      .text {
        font-size: 26rpx;
        font-weight: 400;
        color: #303133;
      }
      .total {
        font-size: 30rpx;
        font-weight: 500;
        color: $edu-price-color;
      }
    }
  }
}

.coupon-wrapper {
  .coupon-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #303133;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .coupon-scroll {
    width: 100%;
    height: 100%;
  }
  .coupon-list {
    padding: 0 30rpx;
    min-height: calc(100% - 100rpx);
    .item {
      & + .item {
        margin-top: 45rpx;
      }
      .title {
        font-size: 28rpx;
        font-weight: 400;
        color: #909399;
      }
    }
    .ticket {
      width: 100%;
      margin-top: 32rpx;
      background-image: var(--bg-img);
      background-size: cover;
      background-repeat: no-repeat;
      .left {
        width: 70%;
        color: var(--main-color);
        .top {
          padding: 0 25rpx;
          font-size: 28rpx;
          .big {
            font-size: 40rpx;
            font-weight: 400;
            margin-right: 10rpx;
          }
        }
        .type {
          font-size: 24rpx;
          margin-top: 18rpx;
          padding: 0 25rpx;
        }
        .date {
          margin-top: 6rpx;
          font-size: 24rpx;
          padding: 0 25rpx;
        }
      }
      .right {
        width: 30%;
        .use {
          width: 150rpx;
          height: 68rpx;
          border-radius: 34rpx;
          border-width: 2rpx;
          border-style: solid;
          color: #ffff;
          font-size: 30rpx;
          line-height: 64rpx;
          text-align: center;
          border-color: var(--main-color);
          background-color: var(--main-color);
          &.active {
            color: var(--main-color);
            border-color: var(--main-color);
            background-color: transparent;
          }
        }
      }
      &.youhui {
        --main-color: #ff8a52;
        --bg-img: url('@/pageCourse/static/images/youhuiquan.png');
      }
      &.dazhe {
        --main-color: #ff9431;
        --bg-img: url('@/pageCourse/static/images/dazhe_bg.png');
      }
    }
  }
  .coupon-btn {
    height: 72rpx;
    background: #ff8a52;
    border-radius: 36px;
    font-size: 32rpx;
    font-weight: 400;
    color: #ffffff;
    margin: 10rpx 55rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.bottom-placeholder {
  height: 98rpx;
}

.bottom-navbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9;
  height: 98rpx;
  padding: 0 30rpx;
  background: #ffffff;
  box-shadow: 0px 2rpx 14rpx 0px rgba(0, 0, 0, 0.06);
  .total {
    margin-left: auto;
    font-size: 26rpx;
    font-weight: 400;
    color: #303133;
    .num {
      font-size: 30rpx;
      font-weight: 500;
      color: #f54030;
    }
  }
  .btn {
    width: 220rpx;
    height: 72rpx;
    @include bg-color();
    border-radius: 39rpx;
    font-size: 32rpx;
    font-weight: 400;
    color: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 28rpx;
  }
}

.coin {
  padding: 30rpx 30rpx 10rpx 30rpx;
  .coin-title {
    height: 45rpx;
    line-height: 45rpx;
    text-align: center;
    font-size: 32rpx;
    color: #303133;
    font-weight: bold;
    margin-bottom: 44rpx;
  }
  .sure {
    height: 72rpx;
    width: 640rpx;
    @include bg-color();
    font-size: 32rpx;
    line-height: 72rpx;
    text-align: center;
    margin: 0 auto;
    color: #ffffff;
    border-radius: 36rpx;
  }
  .radio-item {
    height: auto;
    width: 100%;
    margin-bottom: 56rpx;
    .radio_li {
      display: flex;
      justify-content: space-between;
      .left-ltem {
        height: 44rpx;
        line-height: 44rpx;
        font-size: 30rpx;
        color: #303133;
      }
      .right-item {
        height: 44rpx;
        line-height: 44rpx;
        display: flex;
        .can-num {
          font-size: 26rpx;
          color: #909399;
          margin-right: 23rpx;
        }
      }
    }
  }
}
.addClass {
  font-weight: bold;
}
</style>
